package org.hot100_6.leetcode49;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Solution2 {


    public static void main(String[] args) {
        String [] strs = {"eat","tea","tan","ate","nat","bat"};
        for (List<String> groupAnagram : groupAnagrams(strs)) {
            for (String s : groupAnagram) {
                System.out.println(s);
            }

            System.out.println("---------------");

        }

    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        //统计每个字符串的字符个数

        HashMap<String,List<String>> resMap = new HashMap<>();

        for (String str : strs) {
            int [] count = new int[26];

            int length = str.length();

            for (int i = 0; i < length; i++) {
                count[str.charAt(i)-'a']++;
            }

            StringBuilder sb  = new StringBuilder();

            for (int i = 0; i < 26; i++) {
                if (count[i]>0){
                    char character =(char)('a' +i);
                    sb.append(character);
                    sb.append(count[i]);
                }
            }

            String item  = sb.toString();
            List<String> list = resMap.getOrDefault(item, new ArrayList<>());
            list.add(str);
            resMap.put(item,list);
//            if (resMap.containsKey(item)){
//                List<String> list = resMap.get(item);
//                list.add(str);
//            }else {
//                List<String> list = new ArrayList<>();
//                list.add(str);
//                resMap.put(item,list);
//            }
        }

        ArrayList<List<String>> resList = new ArrayList<>(resMap.values());

        return resList;
    }
}
